package com.sinopec.uhf.model;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.util.SparseArray;

import androidx.annotation.RawRes;

import com.sinopec.uhf.R;
import com.sinopec.uhf.uhfhelp.AppGlobals;

/**
 * @author naz
 * Email 961057759@qq.com
 * Date 2020/4/13
 */
public class BeeperHelper {

    public static SparseArray<Integer> soundId = new SparseArray<>();
    private static SoundPool mSoundPool;

    /**
     * 初始化
     *
     * @param context Context
     */
    public static void init(Context context) {
        // 第一个参数为同时播放数据流的最大个数，第二数据流类型，第三为声音质量
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSoundPool = new SoundPool.Builder()
                    .setAudioAttributes(new AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                            .build())
                    .setMaxStreams(8)
                    .build();

//            val pool = SoundPool.Builder()
//                    .setAudioAttributes(AudioAttributes.Builder()
//                            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
//                            .build())
//                    .setMaxStreams(4)
//                    .build()


        } else {
            mSoundPool = new SoundPool(1, AudioManager.STREAM_ALARM, 1);
        }
        soundId.put(R.raw.beeper, mSoundPool.load(context, R.raw.beeper, 1));
        soundId.put(R.raw.beeper_short, mSoundPool.load(context, R.raw.beeper_short, 1));
    }


    /**
     * 发声
     *
     * @param soundRaw
     */
    public static void beep(@RawRes int soundRaw) {
        if (mSoundPool == null) {
            throw new RuntimeException(AppGlobals.getApplication().getString(R.string.please_initialize_first));
        }
        Integer targetId = soundId.get(soundRaw);
        if (targetId == null) {
            return;
        }
        mSoundPool.play(targetId, 1, 1, 0, 0, 1);
    }

    /**
     * 释放资源
     */
    public static void release() {
        if (mSoundPool != null) {
            mSoundPool.release();
            mSoundPool = null;
        }
    }
}
